package com.bite.friend.service.exam.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.bite.common.core.contants.Constants;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.friend.domain.exam.dto.ExamQueryDTO;
import com.bite.friend.domain.exam.dto.ExamRankDTO;
import com.bite.friend.domain.exam.vo.ExamRankVO;
import com.bite.friend.domain.exam.vo.ExamVO;
import com.bite.friend.domain.user.vo.UserVO;
import com.bite.friend.manager.ExamCacheManager;
import com.bite.friend.manager.UserCacheManager;
import com.bite.friend.mapper.exam.ExamMapper;
import com.bite.friend.mapper.user.UserExamMapper;
import com.bite.friend.service.exam.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ExamServiceImpl  implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private UserCacheManager userCacheManager;



    /**
     * 获取竞赛列表  难点:实现分页  返回结果
     * @param examQueryDTO
     * @return
     */
    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
        List<ExamVO> examVOList = examMapper.selectExamList(examQueryDTO);//当前符合条件的
        return examVOList;
    }


    /**
     * 从reids查询  竞赛列表
     * @param examQueryDTO
     */
    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        //从redis当中获取  竞赛列表的数据
        //新发布的竞赛会给放到缓存中,那老数据呢??
        //第一次,redis没有,可能是老数据,从数据库进行,查到了,就同步到redis
        //第二次,不用再查数据库

        //拿到reids中数据大小
        Long total = examCacheManager.getListSize(examQueryDTO.getType(),null);
        List<ExamVO> examVOList;
        if (total == null || total <=0){
            //没数据,从数据库拿 并且同步
            examVOList = list(examQueryDTO);
            examCacheManager.refreshCache(examQueryDTO.getType(),null);
            total = new PageInfo<>(examVOList).getTotal();
        }else {
            //redis有数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO,null);
            //total拿去方式不一样
            //因为可能redis异常,又重新刷新了
            total = examCacheManager.getListSize(examQueryDTO.getType(),null);
        }
        if (CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        //redis有值才判断

        //检查token是否存在,存在再获取userId
        Long userId = null;
        try {
            userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        }catch (Exception e){
            log.warn("未登录,无法获取token");
        }
        if (userId != null){
            assembleExamVOList(examVOList);
        }
        return TableDataInfo.success(examVOList,total);

    }

    /**
     * 竞赛排名信息
     * @param examRankDTO
     * @return
     */
    @Override
    public TableDataInfo rankList(ExamRankDTO examRankDTO) {
        Long total = examCacheManager.getRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if (total == null || total <=0){
            //没数据,从数据库拿 并且同步
            PageHelper.startPage(examRankDTO.getPageNum(),examRankDTO.getPageSize());
            examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
            examCacheManager.refreshExamRankCache(examRankDTO.getExamId());
            total = new PageInfo<>(examRankVOList).getTotal();
        }else {
            //redis有数据
            examRankVOList = examCacheManager.getExamRankList(examRankDTO);
            //total拿去方式不一样
            //因为可能redis异常,又重新刷新了
        }
        if (CollectionUtil.isEmpty(examRankVOList)){
            return TableDataInfo.empty();
        }
        //redis有值才判断
        //获取昵称
        assembleExamRankVOList(examRankVOList);
        return TableDataInfo.success(examRankVOList,total);

    }

    //获取昵称
    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)){
            return;
        }
        for (ExamRankVO examRankVO :examRankVOList){
            Long userId = examRankVO.getUserId();
            UserVO user = userCacheManager.getUserById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }

    /**
     * 竞赛中的首到题目id
     * @param examId
     * @return
     */
    @Override
    public String getFirstQuestion(Long examId) {
        //先从缓存中拿
//        Long listSize = examCacheManager.getExamQuestionListSize(examId);
//        if (listSize == null || listSize <= 0){
//            examCacheManager.refreshExamQuestionCache(examId);
//        }
        checkAndRefresh(examId);
        return examCacheManager.getFirstQuestion(examId).toString();
    }



    //上一题
    @Override
    public String preQuestion(Long examId, Long questionId) {
        //先查列表
        checkAndRefresh(examId);
        return examCacheManager.preQuestion(examId,questionId).toString();
    }



    //下一题
    @Override
    public String nextQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.nextQuestion(examId,questionId).toString();
    }





    //检查redis中是否存在,不存在,刷新
    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0){
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }

    /**
     * 报名后返回是否报名
     * @param examVOList
     */
    private void assembleExamVOList(List<ExamVO> examVOList){
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);

        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);

        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList){
            if (userExamIdList.contains(examVO.getExamId())){
                examVO.setEnter(true);
            }
        }
    }


}
